package cz.proks.schoolpupilbook.gae.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import cz.proks.schoolpupilbook.gae.converter.Converter;
import cz.proks.schoolpupilbook.gae.converter.UserCourseRelationConverter;
import cz.proks.schoolpupilbook.gae.dao.PersistenceManager.PersistenceExecutor;
import cz.proks.schoolpupilbook.gae.dbo.UserCourseRelationDBO;
import cz.proks.schoolpupilbook.shared.domain.Course;
import cz.proks.schoolpupilbook.shared.domain.User;
import cz.proks.schoolpupilbook.shared.domain.UserCourseRelation;

public class UserCourseRelationDAO extends BaseDAO<UserCourseRelationDBO, UserCourseRelation>{
	@Override
	protected Class<UserCourseRelationDBO> getDBOClass() {		
		return UserCourseRelationDBO.class;
	}
	
	@Override
	protected Converter<UserCourseRelationDBO, UserCourseRelation> getConverter() {
		return new UserCourseRelationConverter();
	}
	
	@Override
	public void save(UserCourseRelation domain) {
		if (!existsForRelation(domain.getUser(), domain.getCourse()))
			super.save(domain);
	}

	public boolean existsForRelation(final User user, final Course course) {
		if (user == null || course == null)
			return false;
		
		return PersistenceManager.execute(new PersistenceExecutor<Boolean>() {
			@Override
			public Boolean doExecute(EntityManager em) {				
				try {
					List<?> res = em.createQuery("SELECT FROM " + getDBOClass().getName() + " WHERE userKey = :userKey AND courseKey = :courseKey")
							 .setParameter("userKey", user.getId())
							 .setParameter("courseKey", course.getId())
							 .getResultList();
					
					return res != null && !res.isEmpty();
				} catch (NoResultException e) {
					return null;
				}				
			}
		}, false);
	}
}
